package calao.client;

import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Widget;

/** A left-side panel that provides shortcut widgets.
 * Shortcuts can be registered via {@link Desktop#register(Shortcut)}. Shortcut
 * registration is usually performed during feature initialization, see
 * {@link DesktopFeature#activate()}.
 */
public class Shortcut 
extends Composite
{

	public final static String STYLE = "calao-Shortcut";
	public final static String MENU_STYLE = "menu";
	public final static String CONTENT_STYLE = "content";

	final Desktop desktop = Desktop.instance;

	final String name;
	final AbstractImagePrototype icon;

	int height = -1;
	int width = -1;
	boolean inited = false;

	final FlowPanel panel = new FlowPanel();
	final FlowPanel menuPanel = new FlowPanel();
	ScrollPanel contentPanel;

	public Shortcut(String name, String title, AbstractImagePrototype icon)
	{
		this.name = name;
		this.icon = icon;
		initWidget(panel);
		setTitle(title);
		addStyleName(STYLE);
		panel.add(menuPanel);
		menuPanel.addStyleName(MENU_STYLE);
	}

	public String getName()
	{
		return name;
	}

	public AbstractImagePrototype getIcon()
	{
		return icon;
	}

	public void init() { }

	void setHeight(int height)
	{
		if (this.height!=height) {
			setHeight(""+height);
			this.height = height;
			resizeContent();
		}
	}

	static void setWidgetWidth(Widget widget, int width, int offset)
	{
		switch (Desktop.getDesktop().getUserAgent()) {
		case UserAgent.GECKO:
			widget.setWidth(""+(width-offset));
			break;
		default:
			widget.setWidth(""+width);
		}
	}

	static void setWidgetHeight(Widget widget, int height, int offset)
	{
		switch (Desktop.getDesktop().getUserAgent()) {
		case UserAgent.GECKO:
			widget.setHeight(""+(height-offset));
			break;
		default:
			widget.setHeight(""+height);
		}
	}

	void setWidth(int width)
	{
		if (this.width!=width) {
			setWidgetWidth(this, width, 2);
			this.width = width;
			resizeContent();
		}
	}

	void setSize(int width, int height)
	{
		setWidth(width);
		setHeight(height);
	}

	public void setContent(Widget widget)
	{
		if (contentPanel==null) {
			contentPanel = new ScrollPanel();
			contentPanel.addStyleName(CONTENT_STYLE);
			panel.add(contentPanel);
			resizeContent();
		}
		contentPanel.clear();
		contentPanel.add(widget);
	}

	public Widget getContent()
	{
		return contentPanel!=null? contentPanel.getWidget() : null;
	}

	public FlowPanel getMenuPanel()
	{
		return menuPanel;
	}

	void resizeContent()
	{
		if (contentPanel!=null && isAttached() && height!=-1 && width!=-1) {
			int usedHeight = contentPanel.getAbsoluteTop() - getAbsoluteTop();
			setWidgetHeight(contentPanel, height - usedHeight, 1);
			setWidgetWidth(contentPanel, width-2, 8);
		}		
	}

}
